package com.personal.system.service.impl.content.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.personal.common.result.PageUtils;
import com.personal.common.result.Result;
import com.personal.system.config.SecurityUtil;
import com.personal.system.entity.content.Note;
import com.personal.system.entity.vo.ApiNoteListVO;
import com.personal.system.exception.GlobalException;
import com.personal.system.mapper.content.NoteMapper;
import com.personal.system.service.content.web.ApiNoteService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class ApiNoteServiceImpl implements ApiNoteService {

    private final NoteMapper noteMapper;

    private final SecurityUtil securityUtil;

    @Override
    public Result selectNoteList(Integer categoryId) {
        Page<ApiNoteListVO> result =  noteMapper.selectPublicNoteList(new Page<ApiNoteListVO>(PageUtils.getPageNo(), PageUtils.getPageSize()),
                categoryId,null);
        result.getRecords().forEach(item ->{
            item.setCreateTimeStr(DateUtil.format(item.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
        });
        return Result.ok(result);
    }

    /**
     * 添加笔记
     * @param note 笔记对象
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertNote(Note note) {
        if (StrUtil.isBlank(note.getContent())) {
            throw new GlobalException(404,"笔记内容不能为空！");
        }
        note.setUserId(securityUtil.getUserIdWeb());
        note.setStatus(2);
        noteMapper.insert(note);
        return Result.ok();
    }

    /**
     * 获取我的笔记列表
     * @return
     */
    @Override
    public Result selectMyNote() {
        Page<ApiNoteListVO> notePage = noteMapper.selectMyNoteList(new Page<>(PageUtils.getPageNo(), PageUtils.getPageSize()),
                securityUtil.getUserIdWeb());
        return Result.ok(notePage);
    }

    /**
     * 删除我的笔记
     * @param id 笔记id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteMyNote(Integer id) {
        Note note = noteMapper.selectById(id);
        if (note == null) {
            throw new GlobalException(404,"笔记不存在!");
        }
        if (!note.getUserId().equals(securityUtil.getUserIdWeb())) {
            throw new GlobalException(404,"只能删除自己的笔记!");
        }
        noteMapper.deleteById(id);
        return Result.ok();
    }
}